<template>
  <div class="oper-log">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item label="操作人员">
          <el-input
            v-model="searchForm.operName"
            placeholder="请输入操作人员"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select
            v-model="searchForm.businessType"
            placeholder="请选择操作类型"
            clearable
            style="width: 150px"
          >
            <el-option label="新增" value="1" />
            <el-option label="修改" value="2" />
            <el-option label="删除" value="3" />
            <el-option label="查询" value="4" />
            <el-option label="导出" value="5" />
            <el-option label="导入" value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="成功" value="0" />
            <el-option label="失败" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <div class="table-header">
        <div class="table-title">操作日志</div>
        <div class="table-actions">
          <el-button type="success" :icon="Download" @click="handleExport">导出</el-button>
          <el-button type="danger" :icon="Delete" @click="handleClean">清空</el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column prop="operId" label="日志ID" width="80" />
        <el-table-column prop="title" label="操作模块" width="120" />
        <el-table-column prop="businessType" label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getBusinessTypeColor(row.businessType)">
              {{ getBusinessTypeText(row.businessType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="method" label="请求方法" width="120" />
        <el-table-column prop="requestMethod" label="请求方式" width="100" />
        <el-table-column prop="operName" label="操作人员" width="100" />
        <el-table-column prop="operUrl" label="请求URL" width="200" show-overflow-tooltip />
        <el-table-column prop="operIp" label="主机地址" width="120" />
        <el-table-column prop="status" label="操作状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : 'danger'">
              {{ row.status === '0' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="costTime" label="消耗时间" width="100">
          <template #default="{ row }">
            {{ row.costTime }}ms
          </template>
        </el-table-column>
        <el-table-column prop="operTime" label="操作时间" width="160" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="操作详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="操作模块">{{ detailData?.title }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getBusinessTypeColor(detailData?.businessType || '')">
            {{ getBusinessTypeText(detailData?.businessType || '') }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请求方法">{{ detailData?.method }}</el-descriptions-item>
        <el-descriptions-item label="请求方式">{{ detailData?.requestMethod }}</el-descriptions-item>
        <el-descriptions-item label="操作人员">{{ detailData?.operName }}</el-descriptions-item>
        <el-descriptions-item label="主机地址">{{ detailData?.operIp }}</el-descriptions-item>
        <el-descriptions-item label="操作地点">{{ detailData?.operLocation }}</el-descriptions-item>
        <el-descriptions-item label="操作状态">
          <el-tag :type="detailData?.status === '0' ? 'success' : 'danger'">
            {{ detailData?.status === '0' ? '成功' : '失败' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="消耗时间">{{ detailData?.costTime }}ms</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ detailData?.operTime }}</el-descriptions-item>
        <el-descriptions-item label="请求URL" :span="2">{{ detailData?.operUrl }}</el-descriptions-item>
        <el-descriptions-item label="请求参数" :span="2">
          <pre>{{ detailData?.operParam }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="返回参数" :span="2">
          <pre>{{ detailData?.jsonResult }}</pre>
        </el-descriptions-item>
        <el-descriptions-item v-if="detailData?.errorMsg" label="错误信息" :span="2">
          <pre style="color: #f56c6c;">{{ detailData?.errorMsg }}</pre>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, Delete } from '@element-plus/icons-vue'
import type { OperLog } from '@/types/monitor'

// 搜索表单
const searchForm = reactive({
  operName: '',
  businessType: '',
  status: '',
  dateRange: []
})

// 表格数据
const tableData = ref<OperLog[]>([])
const loading = ref(false)

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 详情对话框
const detailDialogVisible = ref(false)
const detailData = ref<OperLog | null>(null)

// 获取操作类型颜色
const getBusinessTypeColor = (type: string) => {
  const colors: { [key: string]: 'success' | 'primary' | 'warning' | 'info' | 'danger' } = {
    '1': 'success',
    '2': 'warning',
    '3': 'danger',
    '4': 'info',
    '5': 'primary',
    '6': 'primary'
  }
  return colors[type] || 'info'
}

// 获取操作类型文本
const getBusinessTypeText = (type: string) => {
  const texts: { [key: string]: string } = {
    '1': '新增',
    '2': '修改',
    '3': '删除',
    '4': '查询',
    '5': '导出',
    '6': '导入'
  }
  return texts[type] || '其他'
}

// 获取操作日志列表
const getOperLogList = async () => {
  try {
    loading.value = true
    // 模拟数据
    tableData.value = [
      {
        operId: 1,
        title: '用户管理',
        businessType: '1',
        method: 'addUser',
        requestMethod: 'POST',
        operName: 'admin',
        operUrl: '/system/user',
        operIp: '192.168.1.100',
        operLocation: '北京市',
        status: '0',
        costTime: 150,
        operTime: '2024-01-27 10:30:00',
        operParam: '{"userName":"test","nickName":"测试用户"}',
        jsonResult: '{"code":200,"message":"操作成功"}',
        errorMsg: ''
      },
      {
        operId: 2,
        title: '角色管理',
        businessType: '2',
        method: 'updateRole',
        requestMethod: 'PUT',
        operName: 'admin',
        operUrl: '/system/role',
        operIp: '192.168.1.100',
        operLocation: '北京市',
        status: '0',
        costTime: 200,
        operTime: '2024-01-27 10:25:00',
        operParam: '{"roleId":1,"roleName":"管理员"}',
        jsonResult: '{"code":200,"message":"操作成功"}',
        errorMsg: ''
      },
      {
        operId: 3,
        title: '菜单管理',
        businessType: '3',
        method: 'deleteMenu',
        requestMethod: 'DELETE',
        operName: 'admin',
        operUrl: '/system/menu/1',
        operIp: '192.168.1.100',
        operLocation: '北京市',
        status: '1',
        costTime: 50,
        operTime: '2024-01-27 10:20:00',
        operParam: '{"id":1}',
        jsonResult: '{"code":500,"message":"操作失败"}',
        errorMsg: '菜单下存在子菜单，无法删除'
      }
    ]
    pagination.total = 3
  } catch (error) {
    ElMessage.error('获取操作日志失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  getOperLogList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    operName: '',
    businessType: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 查看详情
const handleView = (row: OperLog) => {
  detailData.value = row
  detailDialogVisible.value = true
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 清空
const handleClean = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有操作日志吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    ElMessage.success('清空成功')
    getOperLogList()
  } catch (error) {
    // 用户取消
  }
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  getOperLogList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.pageNum = page
  getOperLogList()
}

onMounted(() => {
  getOperLogList()
})
</script>

<style lang="scss" scoped>
.oper-log {
  .search-form {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .table-container {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
  }

  .table-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }

  .table-actions {
    display: flex;
    gap: 8px;
  }

  pre {
    background-color: #f5f5f5;
    padding: 8px;
    border-radius: 4px;
    font-size: 12px;
    max-height: 200px;
    overflow-y: auto;
    white-space: pre-wrap;
    word-break: break-all;
  }
}
</style>
